package com.price.common.util

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.pm.ServiceInfo
import android.graphics.Color
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.price.common.extend.context
import com.price.core.R

/**
 * 启动前台服务
 */
fun Service.startForeground(channel: String,foregroundType:Int?) {
    var channelId: String? = null
    // 8.0 以上需要特殊处理
    channelId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel(channel, "ForegroundService")
    } else {
        ""
    }
    val builder = NotificationCompat.Builder(
        this, channelId)
    val notification: Notification = builder.setOngoing(true)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setPriority(NotificationCompat.PRIORITY_MIN)
        .setCategory(Notification.CATEGORY_SERVICE)
        .build()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        startForeground(1, notification, foregroundType?:ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
    } else {
        startForeground(1, notification)
    }
}

/**
 * 创建通知通道
 * @param channelId
 * @param channelName
 * @return
 */
@RequiresApi(Build.VERSION_CODES.O)
fun createNotificationChannel(channelId: String, channelName: String): String {
    val chan = NotificationChannel(
        channelId,
        channelName, NotificationManager.IMPORTANCE_NONE
    )
    chan.lightColor = Color.BLUE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}